package com.example.question.tree.tree1;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @Date 2023-07-09
 * @Author Jonathan
 */
public class Code09_111 {

    public static void main(String[] args) {
        Code09_111 code = new Code09_111();
        TreeNode tree = Tree.createTree(new Integer[]{3, 9, null, null, 20, 15, null, null, 7, null, null});
        System.out.println(Tree.preorderTraversal(tree));
    }


    /**
     * 层次遍历找到第一个叶子节点所在的层次
     *
     * @param root
     * @return
     */
    public int minDepth1(TreeNode root) {
        if (root == null) return 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int minDepth = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.right == null && node.left == null) {
                    return minDepth + 1;
                }
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            minDepth++;
        }
        return minDepth + 1;
    }

    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        if (root.left == null && root.right == null) return 1;
        int left = minDepth(root.left);
        int right = minDepth(root.right);
        if (root.left == null) {
            return right + 1;
        }
        if (root.right == null) {
            return left + 1;
        }
        return Math.min(left, right) + 1;
    }
}
